package com.kaige.asktaoplugin60.handler;

import com.kaige.asktaoplugin60.utils.DataSender;
import com.kaige.asktaoplugin60.utils.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * 玩家连接处理器 - 处理来自游戏客户端的消息
 */
@Slf4j
public class PlayerConnectionHandler extends ChannelInboundHandlerAdapter {
    
    // 连接到游戏服务端的通道
    private final Channel gameServerChannel;
    
    public PlayerConnectionHandler(Channel gameServerChannel) {
        this.gameServerChannel = gameServerChannel;
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 接收到客户端消息
        ByteBuf buf = (ByteBuf) msg;
        byte[] data = new byte[buf.readableBytes()];
        buf.readBytes(data);
        
        // 输出十六进制格式的数据
        String hexData = HexUtil.bytesToHex(data);
        // 获取功能头：data中的第11和12个字节
        byte[] functionHead = new byte[2];
        functionHead[0]= data[10];
        functionHead[1]= data[11];
        String functionHeader = HexUtil.bytesToHex(functionHead);
        // 将消息转发给游戏服务端
        DataSender.sendDataToServer(gameServerChannel, data);
        
        buf.release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("客户端连接发生异常", cause);
        ctx.close();
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端连接断开");
        // 如果客户端断开连接，也关闭与服务端的连接
        if (gameServerChannel != null) {
            gameServerChannel.close();
        }
        ctx.close();
    }
}